package com.whsxt.controller;

import com.github.pagehelper.PageInfo;
import com.whsxt.common.AjaxResult;
import com.whsxt.domain.User;
import com.whsxt.dto.UserDto;
import com.whsxt.service.UserService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

@RequestMapping("/user")
@RestController
@RequiresRoles(value = {"admin", "test"}, logical = Logical.OR)
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/findByPage.do")
    public AjaxResult findByPage(UserDto userDto){
        PageInfo<User> page = userService.findPage(userDto);
        return AjaxResult.ok(page);
    }

    @RequestMapping("/delete.do")
    @RequiresPermissions(value = {"user:delete"})
    public AjaxResult delete(Integer[] id){

        boolean isOk = userService.batchDelete(Arrays.asList(id));
        return isOk ? AjaxResult.ok(): AjaxResult.error("删除失败");
    }

    /**
     * 用户数据新增
     * @param userDto
     * @return
     */
    @RequestMapping("/add.do")
    @RequiresPermissions({"user:delete"})
    public AjaxResult add(UserDto userDto){
        boolean isOk = userService.save(userDto);
        return isOk ? AjaxResult.ok() : AjaxResult.error("新增失败");
    }

    /**
     * 用户数据的修改
     * @param userDto
     * @return
     */
    @RequestMapping("/update.do")
    @RequiresPermissions({"user:update"})
    public AjaxResult update(UserDto userDto){
        boolean isOk = userService.update(userDto);
        return isOk ? AjaxResult.ok() : AjaxResult.error("修改数据失败");
    }

    /**
     * 修改用户的禁用状态
     * @return
     */
    @RequestMapping("/enable.do")
    @RequiresPermissions(("user:update"))
    public AjaxResult enable(Integer id){
        boolean isOk = userService.updateDeleted(id);
        return isOk? AjaxResult.ok(): AjaxResult.error("修改状态失败");
    }

    /**
     * 为用户分配角色
     * @param userId
     * @param roleIds
     * @return
     */
    @RequestMapping("/assign.do")
    @RequiresRoles({"admin"})
    public AjaxResult assign(Integer userId, Integer[] roleIds){
        boolean isOk = userService.assign(userId, roleIds);
        return isOk ? AjaxResult.ok() : AjaxResult.error("分配角色失败");
    }
}
